#/bin/bash

:<<description
功能：Flask 启停查询
描述：

description


#设置脚本异常立即退出
set -e
if [[ ${debug} == 'T' ]]; then set -x; fi
#获取当前脚本名
script=$0
scriptDir=$(cd $(dirname $0); pwd)
#导入通用函数
for file in $(ls ${workDir}/function*.sh); do source ${file}; done
#获取输入参数并命名
action=$1
targetResource=$2
sequence=$3
executeProfile=$4
host=$5
user=$6
#校验命名参数，建议使用正则
#if [[ ! "${action}" ]]; then logger "" "error"; exit 1; fi
#if [[ ! "${resource}" ]]; then logger "" "error"; exit 1; fi
#if [[ ! "${sequence}" ]]; then logger "" "error"; exit 1; fi
#if [[ ! "${executeProfile}" ]]; then logger "" "error"; exit 1; fi
#if [[ ! "${host}" ]]; then logger "" "error"; exit 1; fi
#if [[ ! "${user}" ]]; then logger "" "error"; exit 1; fi
#倒入配置
targetResourceProfile=${workDir}/manager/default-manager/profile.sh
if [[ -f ${targetResourceProfile} ]]; then source ${targetResourceProfile}; fi
targetResourceProfile=${workDir}/manager/${targetResource}-manager/profile.sh
if [[ -f ${targetResourceProfile} ]]; then source ${targetResourceProfile}; fi
targetResourceProfile=${workDir}/manager/${targetResource}-manager/profile-${executeProfile}.sh
if [[ -f ${targetResourceProfile} ]]; then source ${targetResourceProfile}; fi
#其他参数



#判断必须参数非空


function cleanPidFile() {
    local pid
    if [ -f ${appPidFile} ]; then
        pid=$(cat ${appPidFile})
        if ! ps -p ${pid} 2>&1 > /dev/null; then
            rm -f ${appPidFile}
        fi
    fi
}


function status() {

    ppid=$(cat ${appPidFile})
    point=$(date '+%Y-%m-%d %H:%M:%S')

    #echo "${barStar30}${barStar30}${barStar30}${barStar30}"
    #echo "" | awk '{printf "%-30s%-10s%-10s%-10s%-10s%-30s%-60s\n","point","user","pid","%cpu","%mem","start","cmd"}' | sed -nr '/^$/!p'
    #echo "${barStar30}${barStar30}${barStar30}${barStar30}"
    #ps --no-headers -o user,pid,%cpu,%mem,stime,cmd --pid ${ppid} | awk -v point="${point}" '{printf "%-30s%-10s%-10s%-10s%-10s%-30s%-60s\n",point,$1,$2,$3,$4,$5,$6$7$8}' | sed -nr '/^$/!p'
    #ps --no-headers -o user,pid,%cpu,%mem,stime,cmd --ppid ${ppid} | awk -v point="${point}" '{printf "%-30s%-10s%-10s%-10s%-10s%-30s%-60s\n",point,$1,$2,$3,$4,$5,$6$7$8}' | sed -nr '/^$/!p'
    #echo "${barStar30}${barStar30}${barStar30}${barStar30}"


    logger "${barStar30}${barStar30}${barStar30}${barStar30}"
    #表头
    while read -r line; do logger "${line}"; done < <(echo "" | awk '{printf "%-30s%-10s%-10s%-10s%-10s%-30s%-60s\n","point","user","pid","%cpu","%mem","start","cmd"}' | sed -nr '/^$/!p')
    logger "${barStar30}${barStar30}${barStar30}${barStar30}"
    #表身
    while read -r line; do logger "${line}"; done < <(ps --no-headers -o user,pid,%cpu,%mem,stime,cmd --pid ${ppid} | awk -v point="${point}" '{printf "%-30s%-10s%-10s%-10s%-10s%-30s%-60s\n",point,$1,$2,$3,$4,$5,$6$7$8}' | sed -nr '/^$/!p')
    logger "${barStar30}${barStar30}${barStar30}${barStar30}"



}

function terminate(){
    if [[ ! "${appPidFile}" ]]; then logger "Var [appPidFile] is not found."; return 1; fi
    if [[ ! "${targetResourceExecEntry}" ]]; then logger "Var [targetResourceExecEntry] is not found."; return 1; fi
    #是否停止
    cleanPidFile
    if [ ! -f ${appPidFile} ]; then logger "Already terminated."; return 0; fi
    #能否停止
    #停止
    local count=1
    local limit=10s
    while [[ -f ${appPidFile} ]] && (( count <= 10 )); do
        kill $(cat ${appPidFile})
        sleep $(( count * 5 ))s
        (( count = count + 1 ))
        cleanPidFile
    done
    if (( count > limit )); then logger "Failed to terminate."; return 1; fi
    logger "Successfully terminated."
    return 0
}

function startup(){
    if [[ ! "${appPidFile}" ]]; then logger "Var [appPidFile] is not found."; return 1; fi
    if [[ ! "${targetResourceExecEntry}" ]]; then logger "Var [targetResourceExecEntry] is not found."; return 1; fi
    #是否启动
    cleanPidFile
    if [ -f ${appPidFile} ]; then logger "Already started."; return 0; fi
    #能否启动
    #启动
    nohup python3 ${targetResourceExecEntry} > /dev/null 2>&1 &
    echo $! > ${appPidFile}
    local count=1
    local limit=10
    while [[ ! -f ${appPidFile} ]] && (( count <= 10 )); do
        sleep $(( count * 5 ))s
        ppid=$(cat ${appPidFile})
        (( count = count + 1 ))
    done
    if (( count > limit )); then logger "Failed to start."; return 1; fi
    logger "Successfully started."
    return 0
}

function restart() {
    terminate
    if [[ ! $? == 0 ]]; then logger "Failed to terminate when restart."; return 1; fi
    startup
    if [[ ! $? == 0 ]]; then logger "Failed to start when restart."; return 1; fi
    return 0
}

function reload() {
    pass
}

function sshStatus () {
    set +e
    ssh ${user}@${host} "
    resource=${resource}
    appPidFile=${appPidFile}
    targetResourceExecEntry=${targetResourceExecEntry}
    barStar30=${barStar30}
    $(typeset -f checkIpAddress)
    $(typeset -f checkUser)
    $(typeset -f checkRevoker)
    $(typeset -f logger)
    $(typeset -f cleanPidFile)
    $(typeset -f status)
    status
    "
    if [[ ! $? == 0 ]]; then return 1; logger "Ssh status failed." "error"; fi
    logger "Ssh status succeed."
    set -e
    return 0
}

function sshTerminate () {
    set +e
    ssh ${user}@${host} "
    resource=${resource}
    appPidFile=${appPidFile}
    targetResourceExecEntry=${targetResourceExecEntry}
    $(typeset -f checkIpAddress)
    $(typeset -f checkUser)
    $(typeset -f checkRevoker)
    $(typeset -f logger)
    $(typeset -f cleanPidFile)
    $(typeset -f terminate)
    terminate
    "
    if [[ ! $? == 0 ]]; then return 1; logger "Ssh terminate failed." "error"; fi
    logger "Ssh terminate succeed."
    set -e
    return 0
}

function sshStartup () {
    set +e
    ssh ${user}@${host} "
    resource=${resource}
    appPidFile=${appPidFile}
    targetResourceExecEntry=${targetResourceExecEntry}
    $(typeset -f checkRevoker)
    $(typeset -f checkIpAddress)
    $(typeset -f checkUser)
    $(typeset -f logger)
    $(typeset -f cleanPidFile)
    $(typeset -f startup)
    startup
    "
    if [[ ! $? == 0 ]]; then return 1; logger "Ssh start failed." "error"; fi
    logger "Ssh start succeed."
    set -e
    return 0
}

function sshRestart () {
    set +e
    ssh ${user}@${host} "
    resource=${resource}
    appPidFile=${appPidFile}
    targetResourceExecEntry=${targetResourceExecEntry}
    $(typeset -f checkRevoker)
    $(typeset -f checkIpAddress)
    $(typeset -f checkUser)
    $(typeset -f logger)
    $(typeset -f cleanPidFile)
    $(typeset -f terminate)
    $(typeset -f startup)
    $(typeset -f restart)
    restart
    "
    if [[ ! $? == 0 ]]; then return 1; logger "Ssh restart failed." "error"; fi
    logger "Ssh restart succeed."
    set -e
    return 0
}

function sshReload () {
    set +e
    ssh ${user}@${host} "
    resource=${resource}
    appPidFile=${appPidFile}
    targetResourceExecEntry=${targetResourceExecEntry}
    $(typeset -f checkRevoker)
    $(typeset -f checkIpAddress)
    $(typeset -f checkUser)
    $(typeset -f logger)
    $(typeset -f cleanPidFile)
    $(typeset -f reload)
    reload
    "
    if [[ ! $? == 0 ]]; then return 1; logger "Ssh reload failed." "error"; fi
    logger "Ssh reload succeed."
    set -e
    return 0
}


#执行
case ${action} in
    'status') status; ;;
    'terminate') terminate; ;;
    'startup') startup; ;;
    'restart') restart; ;;
    'reload') reload; ;;
    'sshStatus') sshCheck; sshStatus; ;;
    'sshTerminate') sshCheck; sshTerminate; ;;
    'sshStartup') sshCheck; sshStartup; ;;
    'sshRestart') sshCheck; sshRestart; ;;
    'sshReload') sshCheck; sshReload; ;;
    *) logger "Unknown action ${action}."; exit 1; ;;
esac


if [[ ! $? == 0 ]]; then
    logger "${action^} ${targetResource} on ${host:-local} with ${user:-$(whoami)} when ${executeProfile} ${sequence} failed" "error"
    exit 1
fi
logger "${action^} ${targetResource} on ${host:-local} with ${user:-$(whoami)} when ${executeProfile} ${sequence} succeed"


